#!/usr/bin/python
import logging
from parser import parser
from Warehouse import Warehouse 
from Warehouse import box 

from google.appengine.api import mail
class cron:

    ############
    # Initialize
    ############
    def __init__(self, doorplate):
        self.doorplate=doorplate
        self.Ware=Warehouse(self.doorplate)
        self.boxs=dict()

        for k in self.Ware.List():
            pack=self.Ware.CHECKOUT(k)
            if pack is not None:
                self.boxs[k]=parser(box(k).update(eval(pack)))

    ############
    # processing
    ############
    def run(self):
        for v in self.boxs.values():
            v.run()
            #v.keepref()

    ############
    # Saving
    ############
    def flush(self):
        for v in self.boxs.values():
            l,b=v.export()
            self.Ware.CHECKIN(l,b)

    ############
    # output
    ############
    def mail(self):
        for v in self.boxs.values():
            fr,to,tp = v.box.getContact()
            co=v.report()
            if (fr != '') and (to != '') and (co is not None):
                content='-----------------------\n{}\n-----------------------\nSource: {}\n-----------------------'.format(co,v.box.getUrl())
                logging.info(content)
                mail.send_mail(fr,to,tp,content)
